import { ACCESS_TOKEN } from '@/store/mutation-types'
import storage from '@/utils/storage'
import * as LoginApi from '@/api/login'
import * as UserApi from '@/api/user'

// 登陆成功后执行
const loginSuccess = (commit, { token }) => {
  // 过期时间30天
  const expiryTime = 30 * 86400
  // 保存tokne和userId到缓存
  storage.set(ACCESS_TOKEN, token, expiryTime)
  // 记录到store全局变量
  commit('SET_TOKEN', token)
}

export const state = {
  // 用户认证token
  token: '',
  // 用户信息
  userInfo: null,
  roles:[],
  permissions:[],
  userId:'',
  users:[],
  user:null
}

export const mutations = {
  SET_TOKEN: (state, value) => {
    state.token = value
  },
  SET_USERINFO: (state, value) => {
    state.userInfo = value
  },
  SET_USERS: (state, value) => {
    state.users = value
  },
  SET_USER: (state, value) => {
    state.user = value
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}

export const actions = {

  // 用户登录(普通登录: 输入账号、密码和验证码)
  Login({ commit }, data) {
    return new Promise((resolve, reject) => {
      LoginApi.login(data, { custom: { catch: true } }).then(response => {
          const result = response;
          loginSuccess(commit, result)
          resolve(response)
        }).catch(reject)
    })
  },

  // 用户信息
  Info({ commit, state }) {
    return new Promise((resolve, reject) => {
      if (state.userInfo) {
        return resolve(state.userInfo)
      }
      UserApi.getInfo().then(response => {
        const result = response;
		if(result.user)
		{
			const userId = result.user.userId+""
			console.log(userId)
			commit('SET_USER_ID', userId)
		}
		
        commit('SET_USERINFO', result)
		commit('SET_ROLES', result.roles)
		commit('SET_USER', result.user)
		commit('SET_PERMISSIONS', result.permissions)
        resolve(response)
      }).catch(reject)
    })
  },

  // 退出登录
  Logout({ commit }, data) {
    return new Promise((resolve, reject) => {
      LoginApi.logout(data, { custom: { catch: true } }).then(response => {
        storage.remove(ACCESS_TOKEN)
        commit('SET_TOKEN', '')
		commit('SET_USERINFO', '')
		commit('SET_USERS', '')
		commit('SET_USER', '')
		commit('SET_USER_ID', '')
		commit('SET_ROLES', [])
		commit('SET_PERMISSIONS', [])
        resolve(response)
      }).catch(reject)
    })
  },
  
  //初始化用户字典
  users({ commit }, data) {
    return new Promise((resolve, reject) => {
      UserApi.selectUserDict(data, { custom: { catch: true } }).then(response => {
		  uni.setStorageSync('users', response.rows);//将名字存入缓存
          resolve(response) 
        }).catch(reject)
    })
  },

}
